package com.demo.shiro;

import java.util.HashSet;
import java.util.Set;

import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authc.UnknownAccountException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.springframework.beans.factory.annotation.Autowired;

import com.demo.entity.User;
import com.demo.service.UserService;

public class MyShiroRealm extends AuthorizingRealm {
	@Autowired
	private UserService userService;

	/**
	 * 加密,在ShiroConfiguration中会调用
	 */
	@Override
	protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
		System.out.println("MyShiroRealm的doGetAuthenticationInfo运行");
		// 强制转换
		UsernamePasswordToken uptoken = (UsernamePasswordToken) token;
		// 获取表单userName
		String userName = uptoken.getUsername();
		// 从数据库查找此人是否存在
		User user = userService.selectByUserName(userName);
		// 如果用户名不存在则抛异常
		if (user == null) {
			throw new UnknownAccountException("用户名不存在");
		}
		// 认证的实体信息，可以是username，也可以是用户的实体类对象
		Object principal = user;
		// 加盐加密,可以用用户名
		ByteSource credentialsSalt = ByteSource.Util.bytes(user.getUsername());
		// 获取当前realm对象
		String realmName = this.getName();
		// 创建SimpleAuthenticationInfo对象，并且把username和password等信息封装到里面
		// 用户密码的比对是Shiro帮我们完成的
		SimpleAuthenticationInfo info = null;
		info = new SimpleAuthenticationInfo(principal, user.getPassword(), credentialsSalt, realmName);
		return info;
	}

	/**
	 * 授权
	 */
	@Override
	protected AuthorizationInfo doGetAuthorizationInfo (PrincipalCollection principals) {
		System.out.println("MyShiroRealm的doGetAuthorizationInfo运行");
		// 从PrincipalCollection中获得用户信息
		//principal的值对应的是实体类还是字符串，取决于在doGetAuthenticationInfo（）中	Object principal = user这句话中放入的是实体还是字符串
		User principal =(User) principals.getPrimaryPrincipal();
		System.out.println("principals的值为："+principal.toString());
		
		// 根据用户名来查询数据库赋予用户角色,权限(需要查询数据库，在这里是写死的，需要考虑到一个用户多个角色与权限)
		Set<String> roles = new HashSet<>();
		Set<String> permissions = new HashSet<>();
		roles.add("user");
		permissions.add("user");
		if ("admin".equals(principal.getUsername())) {
			roles.add("admin");
			permissions.add("admin");
		}
		SimpleAuthorizationInfo info = new SimpleAuthorizationInfo(roles);
		//添加权限
		info.setStringPermissions(permissions);
		return info;
	}

}
